﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace Fis.Win.Rules
{
    public class ImportViewProvider : ClientViewProvider
    {
        public override System.Collections.Hashtable InitializeViewModel(System.Collections.Hashtable args)
        {
            return args ?? new System.Collections.Hashtable();
        }

        public override bool ExecuteUpdate(System.Collections.Hashtable viewModel)
        {
            var exec = false;
            if (!viewModel["TransType"].Equals(0))
            {
                var param = Fis.Win.Utils.AppSession.CreateServiceParamter(viewModel);
                param["data"] = Agile.Engine.Utils.ZipUtils.ZipDataTable(param["data"] as System.Data.DataTable);
                exec = InvokeService(param);
                View.Message = ServiceProcess.Message;
                if (exec)
                {
                    if (ServiceProcess.Result.ContainsKey("data"))
                        ProcessLocal(param["TransType"].ToString(), param["ImportType"].ToString());
                }
            }
            else
            {
                exec = ExecuteBill(viewModel["data"] as DataTable, viewModel["ImportType"].ToString());
            }
            return exec;
        }

        bool ExecuteBill(DataTable schema, string importType)
        {
            //转换成凭证主从表
            var master = DataContext.DefaultModel.QueryTable("TBILLMASTER", "1=2");
            var detail = DataContext.DefaultModel.QueryTable("TBILLDETAIL", "1=2");

            try
            {

                foreach (var d in schema.AsEnumerable())
                {
                    var mstCount = master.Compute("Count(FSEQUENCE)", string.Format("FSEQUENCE='{0}'", d["FSEQUENCE"]));
                    if (Fis.Win.Utils.ReportUtils.NullParse(mstCount) > 0)
                        continue;

                    var mstRow = master.NewRow();
                    foreach (DataColumn mc in master.Columns)
                    {
                        if (schema.Columns.Contains(mc.ColumnName))
                            mstRow[mc.ColumnName] = d[mc.ColumnName];
                    }
                    var newGuid = Guid.NewGuid().ToString();
                    mstRow["SID"] = newGuid;
                    mstRow["FSTATUS"] = 4;
                    var sequnce = 0;

                    foreach (var dtl in schema.Select(string.Format("FSEQUENCE='{0}'", d["FSEQUENCE"])))
                    {
                        var dtlRow = detail.NewRow();
                        foreach (DataColumn dc in detail.Columns)
                        {
                            if (schema.Columns.Contains(dc.ColumnName))
                                dtlRow[dc.ColumnName] = dtl[dc.ColumnName];
                        }
                        dtlRow["SID"] = string.Format("{0}-{1:0000#}", newGuid.GetHashCode(), ++sequnce);
                        dtlRow["FVCHID"] = newGuid;
                        detail.Rows.Add(dtlRow);
                    }

                    master.Rows.Add(mstRow);

                }
                //更新数据

                DataContext.DefaultModel.ExecuteTransaction(

                                () =>
                                {
                                    if (importType.Equals("1"))
                                    {
                                        DataContext.DefaultModel.Delete(detail.TableName, "FVCHID in (SELECT SID FROM TBILLMASTER WHERE FSTATUS=4)");
                                        DataContext.DefaultModel.Delete(master.TableName, "FSTATUS=4");
                                    }

                                    new Agile.Engine.Data.DataAccess() { Context = DataContext, TableName = master.TableName }.AddNew(master.Select());
                                    new Agile.Engine.Data.DataAccess() { Context = DataContext, TableName = detail.TableName }.AddNew(detail.Select());
                                });

            }
            catch (Exception ex)
            {
                View.Message = ex.Message;
                return false;
            }
            return true;
        }

        void ProcessLocal(string transType, string importType)
        {

            switch (transType)
            {
                case "1":
                    var acc = Agile.Engine.Utils.ZipUtils.UnZipDataTable(ServiceProcess.Result["data"].ToString());
                    acc.TableName = "TACCOUNT";
                    DataContext.DefaultModel.ExecuteTransaction(

                            () =>
                            {
                                if (importType.Equals("1"))
                                {
                                    DataContext.DefaultModel.Delete(acc.TableName, "FFIXEDACCOUNT=0 or FFIXEDACCOUNT is null");
                                }

                                new Agile.Engine.Data.DataAccess() { Context = DataContext, TableName = acc.TableName }.AddNew(acc.Select());
                            });
                    Fis.Win.Utils.CacheContext.RefreshCache(acc.TableName);
                    break;
                case "2":
                    var aids = Agile.Engine.Utils.ZipUtils.UnZipDataTable(ServiceProcess.Result["data"].ToString());
                    aids.TableName = "TAIDS";
                    DataContext.DefaultModel.ExecuteTransaction(

                            () =>
                            {
                                if (importType.Equals("1"))
                                {
                                    DataContext.DefaultModel.Delete(aids.TableName, "1=1");
                                }

                                new Agile.Engine.Data.DataAccess() { Context = DataContext, TableName = aids.TableName }.AddNew(aids.Select());
                            });
                    Fis.Win.Utils.CacheContext.RefreshCache(aids.TableName);
                    break;
                case "3":
                    var rate = Agile.Engine.Utils.ZipUtils.UnZipDataTable(ServiceProcess.Result["data"].ToString());
                    rate.TableName = "TRATE";
                    DataContext.DefaultModel.ExecuteTransaction(

                            () =>
                            {
                                if (importType.Equals("1"))
                                {
                                    DataContext.DefaultModel.Delete(rate.TableName, "FISBASE is null or FISBASE != 1");
                                }

                                new Agile.Engine.Data.DataAccess() { Context = DataContext, TableName = rate.TableName }.AddNew(rate.Select());
                            });
                    Fis.Win.Utils.CacheContext.RefreshCache(rate.TableName);
                    break;
            }
        }
    }
}
